import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '@/views/login/index'
import Layout from '@/views/layout'
import NotFound from '@/views/404'
import Search from '@/views/search'
import SearchResult from '@/views/search/result'
import Article from '@/views/article'
import UserEdit from '@/views/layout/user/edit'
import Chat from '@/views/layout/user/chat'

// 导入二级路由
import Home from '@/views/layout/home'
import QA from '@/views/layout/qa'
import Video from '@/views/layout/video'
import User from '@/views/layout/user'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
<<<<<<< HEAD

=======
  {
    path: '/',
    component: Layout,
    redirect: '/home', // 重定向
    // 二级路由
    children: [
      {
        path: 'home',
        component: Home,
        meta: { isKeepAlive: true }
      },
      {
        path: 'qa',
        component: QA
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result',
    component: SearchResult
  },
  {
    path: '/user/edit',
    component: UserEdit
  },
  {
    path: '/article/:id',
    component: Article
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '*',
    component: NotFound
  }
>>>>>>> layout
]

const router = new VueRouter({
  routes
})

// 需要拦截的页面(需要登录才可以访问到)
const loginURL = ['/user', '/qa', '/user/edit']

router.beforeEach(function (to, from, next) {
  const token = store.state.user.token.token
  // console.log(token)

  if (token) {
    next()
  } else {
    // 没有token
    if (loginURL.some((item) => to.path === item)) {
      // if成立，需要登录
      // next('/login')
      // router.push('/login')
      // 带上回来的地址
      router.push({
        path: '/login',
        query: {
          back: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})

export default router
